package SM2;

import com.alibaba.fastjson2.JSON;
import org.bouncycastle.asn1.gm.GMNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.math.ec.ECFieldElement;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.math.ec.custom.gm.SM2P256V1Point;

import java.math.BigInteger;
import java.util.Random;

// SM2算法是基于ECC的非对称加密算法
public class SM2 {
    private static final X9ECParameters sm2p256v1 = GMNamedCurves.getByName("sm2p256v1");
    private static final Random RND = new Random();
    private static final ECPoint G = sm2p256v1.getG();
    ;
    private BigInteger sk;
    private ECPoint pk;

    public BigInteger getSk() {
        return sk;
    }

    public ECPoint getPk() {
        return pk;
    }

    public void generateKey() {
        // 生成一个属于[1,n-2]的整数 d
        BigInteger d = BigInteger.valueOf(RND.nextLong());
        ECPoint P = G.multiply(d);
        sk = d;
        pk = P;
    }

    public void encrypt(byte[] plaintext, ECPoint pk) {
        // 生成一个[1,n-1]的随机值k
        BigInteger k = BigInteger.valueOf(RND.nextLong());
        ECPoint C1 = G.multiply(k);
        // 将C1数据类型转换为比特串
        byte[] C1Bytes = JSON.toJSONBytes(C1);

        ECPoint Q = pk.multiply(k);
        // 通过Q获取(x2,y2)，将x2,y2转换为比特串
        byte[] QBytes = JSON.toJSONBytes(Q);

    }
}
